package com.hisense.settings.channel;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.text.TextUtils;

import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.VideoInputSettingsActivity;
import com.hisense.settings.MyLog;
import com.hisense.settings.ParentalLockPassword;
import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.Wrapper;
import com.hisense.settings.PowerOnSettings;
/*import com.marvell.willowtv.framework.features.ParentalControl;
import com.marvell.willowtv.framework.features.Tuner;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.model.atsc.USDTVPCData;
import com.marvell.willowtv.framework.util.atsc.ErrorCodes;
import com.marvell.willowtv.framework.util.atsc.InputSourceType;*/

public class ChannelSettings extends SettingsPreferenceFragment{

    private static final String TAG = "ChannelSettings";

    private static final String KEY_TUNER_MODE = "tuner_mode";
    private static final String KEY_AUTO_SCAN_CABLE = "auto_scan_cable";
    private static final String KEY_AUTO_SCAN_ANTENNA = "auto_scan_antenna";
    private static final String KEY_AUTO_SCAN_BOX = "auto_scan_box";
	private static final String KEY_CHANNEL_MANAGEMENT = "channel_management";
    private static final String KEY_CHANNEL_SKIP = "channel_skip";
	private static final String KEY_FAVORITE_LIST = "favorite_list";
	private static int ParentLockPasswordRequestCode = 65;
	
	// holds the context of the activity
    private Context mContext;
    //private Tuner mTuner;
	
    private static final int DIALOG_CHANNEL_SKIP_LIST = 10;
	private static final int DIALOG_FAVORITE_LIST = 11;

    private ListPreference mTunerModePreference;

    private PreferenceScreen mAutoScanCable;
	private PreferenceScreen mAutoScanAntenna;
    private PreferenceScreen mAutoScanBox;
	
    private PreferenceScreen mChannelSkipPreference;
	private PreferenceScreen mFavoriteListPreference;

    private Map<Integer, Long> mChannelsMap =
        new HashMap<Integer, Long>();

	private Map<Integer, Long> mFavoriteListMap =
        new HashMap<Integer, Long>();

	private boolean isTuner = false;
	private static Thread autoAntennaThread = null;
	private static Thread autoCableThread = null;
	
	private BroadcastReceiver mEventReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(TvIntents.INTENT_SOURCE_BIND_CHANGE)){
				isTuner = Wrapper.getWrapperInstance().isTunerInput();
				MyLog.d(TAG, "isTuner:"+isTuner);
				mTunerModePreference.setEnabled(isTuner);
				mAutoScanCable.setEnabled(isTuner);
				mAutoScanAntenna.setEnabled(isTuner);
				mAutoScanBox.setEnabled(isTuner);
				mChannelSkipPreference.setEnabled(isTuner);
			}
			
		}};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getActivity().setTitle(R.string.channel_settings);
		mContext = getActivity();
        //mTuner = TvFramework.getInstance().getTunerInstance();
		addPreferencesFromResource(R.xml.channel_settings);
		mTunerModePreference = (ListPreference) findPreference(KEY_TUNER_MODE);
		final int currentTunerMode = Wrapper.getWrapperInstance().getTunerMode();
		mTunerModePreference.setValue((String.valueOf(currentTunerMode)));
        mTunerModePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				 final String key = preference.getKey();
					if (KEY_TUNER_MODE.equals(key)) {
						int value = Integer.parseInt((String) newValue);
			            try {
			            	MyLog.d(TAG, " tuner mode setting:"+value);
			                Wrapper.getWrapperInstance().setContext(mContext);
			                Wrapper.getWrapperInstance().setTunerMode(value);
							updateTunerModeSummary(value);
							
							refreshPowerOnChannel();
			            } catch (NumberFormatException e) {
			                Log.e(TAG, "could not persist tuner mode setting", e);
			            }

					}
			        return true;
			}
		});
		updateTunerModeSummary(currentTunerMode);

        mAutoScanCable = (PreferenceScreen) findPreference(KEY_AUTO_SCAN_CABLE);		
		mAutoScanAntenna = (PreferenceScreen) findPreference(KEY_AUTO_SCAN_ANTENNA);
        mAutoScanBox = (PreferenceScreen) findPreference(KEY_AUTO_SCAN_BOX);	
        mChannelSkipPreference = (PreferenceScreen) findPreference(KEY_CHANNEL_SKIP);		
		mFavoriteListPreference = (PreferenceScreen) findPreference(KEY_FAVORITE_LIST);
		
		PreferenceGroup channelmanagement = (PreferenceGroup)findPreference(KEY_CHANNEL_MANAGEMENT);		
		channelmanagement.removePreference(mFavoriteListPreference);
		
		//add for refresh CC
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(TvIntents.INTENT_SOURCE_BIND_CHANGE);
		mContext.registerReceiver(mEventReceiver, intentFilter);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		isTuner = Wrapper.getWrapperInstance().isTunerInput();
		mTunerModePreference.setEnabled(isTuner);
		mAutoScanCable.setEnabled(isTuner);
		mAutoScanAntenna.setEnabled(isTuner);
		mAutoScanBox.setEnabled(isTuner);
		mChannelSkipPreference.setEnabled(isTuner);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mEventReceiver!=null){
			mContext.unregisterReceiver(mEventReceiver);
		}
	}
	private void refreshPowerOnChannel() {
		// refresh power on channel by tuner mode
		int tunerMode = Wrapper.getWrapperInstance().getTunerMode();
		String channelUriString;
		if (tunerMode == 0) { //antenna
			channelUriString = Settings.Secure.getString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI_ANTENNA);
			Log.d(TAG, "channelUriString!!!!!!!!!!"+channelUriString );
		} else { //cable
			channelUriString = Settings.Secure.getString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI_CABLE);
			Log.d(TAG, "channelUriString###########"+channelUriString );
		}
		if(TextUtils.isEmpty(channelUriString)){
			Settings.Secure.putInt(getContentResolver(),"power_on_source_num", 0);
			Log.d(TAG, "TextUtils.isEmpty(channelUriString)1:" +TextUtils.isEmpty(channelUriString));			
		}else{
			Settings.Secure.putInt(getContentResolver(),"power_on_source_num", 1);
		}
		Settings.Secure.putString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI, channelUriString);
	}
	
	@Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {

		if (preference == mChannelSkipPreference) {
			Intent intent = new Intent("com.android.settings.CHANNEL_SKIP_LIST");
			mContext.startActivity(intent);
		} 
		else if (preference == mFavoriteListPreference) {
			Intent intent = new Intent("com.android.settings.FAVORITE_LIST");
			mContext.startActivity(intent);
		}
		else if (preference == mAutoScanCable) {
			if (getParentalLockStatus()){
                Intent pinintent = new Intent(mContext, ParentalLockPassword.class);
                pinintent.setAction("com.android.parentallock.ACTION_VERIFY_PASSWORD");
                Bundle bundle = new Bundle();
                bundle.putString("ActivityIntent", "Channel");
                bundle.putInt("TunerMode", 1);
                pinintent.putExtras(bundle);
                startActivityForResult(pinintent, ParentLockPasswordRequestCode);
            }else{
            	//setTunerModeTask MysetTunerModeTask=new setTunerModeTask(1);
            	//MysetTunerModeTask.execute();
            }
		}
		else if (preference == mAutoScanAntenna) {
			if (getParentalLockStatus()){
                Intent pinintent = new Intent(mContext, ParentalLockPassword.class);
                pinintent.setAction("com.android.parentallock.ACTION_VERIFY_PASSWORD");
                Bundle bundle = new Bundle();
                bundle.putString("ActivityIntent", "Channel");
                bundle.putInt("TunerMode", 0);
                pinintent.putExtras(bundle);
                startActivityForResult(pinintent, ParentLockPasswordRequestCode);
            }else{
            	//setTunerModeTask MysetTunerModeTask=new setTunerModeTask(0);
            	//MysetTunerModeTask.execute();
            }
		}
		else if (preference == mAutoScanBox) {
			Intent intent = new Intent(mContext, VideoInputSettingsActivity.class);
			mContext.startActivity(intent);
		}
		else
		{
			return super.onPreferenceTreeClick(preferenceScreen, preference);
		}


		return true;
    }

    /*public boolean onPreferenceChange(Preference preference, Object objValue) {
        final String key = preference.getKey();
		if (KEY_TUNER_MODE.equals(key)) {
			int value = Integer.parseInt((String) objValue);
            try {
            	MyLog.d(TAG, " tuner mode setting:"+value);
                Wrapper.getWrapperInstance().setContext(mContext);
                Wrapper.getWrapperInstance().setTunerMode(value);
				updateTunerModeSummary(value);
				
				refreshPowerOnChannel();
            } catch (NumberFormatException e) {
            	MyLog.e(TAG, "could not persist tuner mode setting");
            	Log.e(TAG, "could not persist tuner mode setting", e);
            }

		}
        return true;
    }*/
    private void updateTunerModeSummary(int value) {
		int index = mTunerModePreference.findIndexOfValue(String.valueOf(value));
		MyLog.d(TAG, " index"+index);
		if(index != -1){
			mTunerModePreference.setSummary(mContext.getResources().getStringArray(R.array.tuner_mode_entries)[index]);
		}
    }
    @Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_CHANNEL_SKIP_LIST:
			{
				final ChannelSkippedListener listener = new ChannelSkippedListener(true);
				final CancelListener mCancelListener = new CancelListener();
				final AlertDialog.Builder builder =
					new AlertDialog.Builder(mContext)
				.setTitle(R.string.channel_skip)
				.setPositiveButton(android.R.string.ok, listener)
				.setOnCancelListener(mCancelListener)
				.setNegativeButton(android.R.string.cancel, mCancelListener);	
				return builder.create();
			}
			case DIALOG_FAVORITE_LIST:
			{
				final FavoriteListListener listener = new FavoriteListListener(true);
				final CancelListener mCancelListener = new CancelListener();
				final AlertDialog.Builder builder =
					new AlertDialog.Builder(mContext)
							.setTitle(R.string.favorite_list)
							.setPositiveButton(android.R.string.ok, listener)
							.setOnCancelListener(mCancelListener)
							.setNegativeButton(android.R.string.cancel, mCancelListener);
				return builder.create();
			}
		}
		return null;
	}
    private class CancelListener
    implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
        //finish();
    		}
    	@Override
    	public void onCancel(DialogInterface dialog) {
        //finish();
    		}
    	}
    private class ChannelSkippedListener implements
    DialogInterface.OnClickListener, DialogInterface.OnMultiChoiceClickListener {
    	private int mCurrentIndex;
    	private Set<Integer> mSelectedIndexSet;
    	public ChannelSkippedListener(boolean multipleSelect) {
    		mCurrentIndex = 0;
    		if (multipleSelect) {
    			mSelectedIndexSet = new HashSet<Integer>();
    			}
    		}
    	public void onClick(DialogInterface dialog, int which) {
    		if (which == DialogInterface.BUTTON_POSITIVE) {
    			if (mSelectedIndexSet != null) {
    				final int size = mChannelsMap.size();
    				// We'd like to sort the files by its index, so we do not use Set iterator.
    				for (int i = 0; i < size; i++) {
    					if (mSelectedIndexSet.contains(i)) {
    						Long id = mChannelsMap.get(i);
    						}
    					}
    				}
    			} else if (which == DialogInterface.BUTTON_NEGATIVE) {
    				finish();
    				} else {
    					// Some file is selected.
    					mCurrentIndex = which;
    					if (mSelectedIndexSet != null){
    						if (mSelectedIndexSet.contains(which)){
    							mSelectedIndexSet.remove(which);
    							} else {
    								mSelectedIndexSet.add(which);
    								}
    						}
    					}
    		}
    	public void onClick(DialogInterface dialog, int which, boolean isChecked){
    		if (mSelectedIndexSet == null || (mSelectedIndexSet.contains(which) == isChecked)){
    			} else {
    				onClick(dialog, which);
    				}
    		}
    	}
    private class FavoriteListListener implements
    DialogInterface.OnClickListener, DialogInterface.OnMultiChoiceClickListener {
    	private int mCurrentIndex;
    	private Set<Integer> mSelectedIndexSet;
    	public FavoriteListListener(boolean multipleSelect){
    		mCurrentIndex = 0;
    		if (multipleSelect){
    			mSelectedIndexSet = new HashSet<Integer>();
    			}
    		}
    	public void onClick(DialogInterface dialog, int which) {
    		if (which == DialogInterface.BUTTON_POSITIVE) {
    			if (mSelectedIndexSet != null) {
    				final int size = mFavoriteListMap.size();
    				// We'd like to sort the files by its index, so we do not use Set iterator.
    				for (int i = 0; i < size; i++) {
    					if (mSelectedIndexSet.contains(i)) {
    						Long id = mFavoriteListMap.get(i);
    						}
    					}
    				}
    			} else if (which == DialogInterface.BUTTON_NEGATIVE) {
    				finish();
    				} else {
    					// Some file is selected.
    					mCurrentIndex = which;
    					if (mSelectedIndexSet != null) {
    						if (mSelectedIndexSet.contains(which)) {
    							mSelectedIndexSet.remove(which);
    							} else {
    								mSelectedIndexSet.add(which);
    								}
    						}
    					}
    		}
    	public void onClick(DialogInterface dialog, int which, boolean isChecked) {
    		if (mSelectedIndexSet == null || (mSelectedIndexSet.contains(which) == isChecked)) {
    			
    		} else {
    			onClick(dialog, which);
    			}
    		}
    	}
   
    /*private class setTunerModeTask extends AsyncTask<Void, Integer, Integer>{

    	int Res=ErrorCodes.FAILURE;
    	int TunerModesummary = Wrapper.getWrapperInstance().getTunerMode();
    	private setTunerModeTask(int modesummary) {  
            super();
            this.TunerModesummary=modesummary;
            MyLog.d(TAG, "setTunerModeTask->TunerModesummary:"+TunerModesummary);
        } 
		@Override
		protected Integer doInBackground(Void... params) {
			if(TunerModesummary==0){
				Res=mTuner.setTunerMode(InputSourceType.ATSC_INPUT, mContext);
				Settings.Secure.putString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI_ANTENNA, "");
			}
			else{
				Res=mTuner.setTunerMode(InputSourceType.CABLE_INPUT, mContext);
				Settings.Secure.putString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI_CABLE, "");
			}
			Settings.Secure.putString(getContentResolver(), PowerOnSettings.KEY_POWER_ON_CHANNEL_URI, "");
			
			try {
                Thread.sleep(5);
                if (isCancelled()) {
                    MyLog.d(TAG, "setTunerModeTask cancelled");
                    return ErrorCodes.FAILURE;
                }
			} catch (InterruptedException e) {
                e.printStackTrace();
            }
			return Res;
		}
		@Override  
	    protected void onProgressUpdate(Integer... progress) {  
			MyLog.d(TAG,"onProgressUpdate->progress:"+ progress[0]);  
	    }  
	  
	    @Override  
	    protected void onPostExecute(Integer result) {  
	    	MyLog.d(TAG,"onPostExecute->result:"+ result);
	        if(Res==ErrorCodes.SUCCESS){
                	mTunerModePreference.setValue((String.valueOf(TunerModesummary)));
    				updateTunerModeSummary(TunerModesummary);
                	Intent intent = new Intent(mContext, AutoScanActivity.class);
    				mContext.startActivity(intent);
	        }else{
	        	MyLog.d(TAG,"onPostExecute SetTunerMode failed !!!");
	        }
	    }     
    }*/

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		//super.onActivityResult(requestCode, resultCode, data);
		MyLog.d(TAG, "resultCode = " + resultCode);
        if (requestCode == ParentLockPasswordRequestCode) {
        	MyLog.d(TAG, "PIN_REQUEST_OLD");
            if (resultCode == Activity.RESULT_CANCELED) {
            	int TunerMode = Wrapper.getWrapperInstance().getTunerMode();
            	MyLog.d(TAG, "TunerMode:"+TunerMode);
            	mTunerModePreference.setValue((String.valueOf(TunerMode)));
				updateTunerModeSummary(TunerMode);
            } else if (resultCode == Activity.RESULT_OK) {
            	MyLog.d(TAG, "Intent data:"+data);
            	if(data!=null){
            		int TunerModesummary =data.getIntExtra("TunerMode", Wrapper.getWrapperInstance().getTunerMode());
            		MyLog.d(TAG, "TunerModesummary:"+TunerModesummary);
            		//setTunerModeTask MysetTunerModeTask=new setTunerModeTask(TunerModesummary);
                	//MysetTunerModeTask.execute();
            	}
            }
        }
	}
	
    /**
     * return the current status of parental control
     */
    private boolean getParentalLockStatus() {
        /*ParentalControl mParentalControl = TvFramework.getInstance()
                .getParentalControlInstance();
        final USDTVPCData pcData = mParentalControl.getParentalSettings();

        if (pcData != null) {
            return pcData.isPcEnable();
        }*/
        return false;
    }
	
    }
